<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="/sys/base :: headFragment(~{::title},~{::link},~{::style})"></head>
<body>
<div class="layui-form base-dialog">
    <form class="layui-form">
        <div id="permission"></div>
        <div class="layui-form-item base-finally">
            <button class="layui-btn" lay-submit lay-filter="saveAuthorization"><i class="fa fa-check-circle"></i> 保存
            </button>
            <button class="layui-btn btn-secondary base-close-dialog"><i class="fa fa-times-circle"></i> 关闭</button>
        </div>
    </form>
</div>
</body>
<script th:replace="/sys/base :: scriptFragment"></script>
<script type="text/javascript" th:inline="javascript">
    layui.use(['jquery', 'layer', 'tree', 'form'], function () {
        var $ = layui.jquery;
        var tree = layui.tree;
        var form = layui.form;

        var adminId = [[${adminId}]]; // 用户编号

        var children = [];
        var roleList = [[${roleList}]];
        roleList.forEach(function (item) {
            children.push({id: item.id, title: item.roleName, checked: item.baseAdminId === adminId});
        });

        var sysUserTree = tree.render({ // 创建tree
            elem: '#permission'
            , id: "permission"
            , showCheckbox: true
            , spread: true
            , data: [{
                id: 0
                , title: '全选'
                , spread: true
                , children: children
            }]
        });

        form.on('submit(saveAuthorization)', function (data) { // TODO 提交表单
            data.field.createUserAccount = [[${#authentication.principal.username}]]; // 创建者账号
            data.field.id = adminId; // 用户编号
            var checkedDom = tree.getChecked('permission'); // tree选中的DOM
            var checkedIdArray = $.getTreeIdLI(checkedDom).splice(1);
            data.field.baseAdminRoleId = checkedIdArray.join(","); // 角色编号
            $.ajax({
                url: $.getProjectNameLI() + "/sys/admin/authorization",
                async: false,
                type: "post",
                dataType: "json",
                data: data.field,
                success: function (res) {
                    if (res.code === 0) {
                        layer.msg("授权成功", {time: 1500}, function () {
                            parent.layer.close(window.parent.layerIndex);
                            window.top.location.reload();
                        });
                    } else {
                        layer.msg(res.message, {time: 1500});
                    }
                }
                , complete: function (xhr) {
                    $.ajaxCompleteLI(xhr);
                }
            });
            return false;
        });
    });
</script>
</html>